package com.tianxiabuyi.weixin.qy.contact;


import com.alibaba.fastjson.annotation.JSONField;
import com.tianxiabuyi.utils.JSONUtil;
import com.tianxiabuyi.weixin.common.WxClient;
import com.tianxiabuyi.weixin.qy.QyWxClientFactory;
import com.tianxiabuyi.weixin.qy.contact.user.*;

import java.util.List;
import java.util.Set;

/**
 * 用户管理
 */
public class Users {


    private WxClient wxClient;

    /**
     * 初始化wxclient
     * @param corpId
     * @param corpSecret
     * @return
     */
    public static Users with(String corpId, String corpSecret)  {
        Users users = new Users();
        users.setWxClient(QyWxClientFactory.getInstance().with(corpId, corpSecret));
        return users;
    }

    /**
     * 设置wxclient，如果已使用with初始化，则不用调用该方法
     * @param wxClient
     */
    public void setWxClient(WxClient wxClient) {
        this.wxClient = wxClient;
    }

    /**
     * 根据userid获取用户的详细信息
     * @param uid
     * @return
     */
    public ReadUser get(String uid) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?userid=%S";
        String user = wxClient.get(String.format(url, uid));
        return JSONUtil.fromJson(user, ReadUser.class);
    }

    /**
     * 添加用户
     * @param user
     */
    public void create(CreateUser user) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create";
        String json = JSONUtil.toJson(user);
        wxClient.post(url, json);
    }

    /**
     *  更新用户信息
     * @param user
     */
    public void update(UpdateUser user) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update";
        String json = JSONUtil.toJson(user);
        wxClient.post(url, json);
    }

    /**
     * 根据userid删除用户
     * @param uid
     */
    public void delete(String uid) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?userid=%s";
        wxClient.get(String.format(url, uid));
    }

    /**
     * 获取指定部门内（是否包含子部门）中各种状态的人员列表， FOLLOWED(1), UN_FOLLOWED(4), SUSPEND(2), UNKNOWN(-1);
     * @param department
     * @param fetchChild
     * @param statusSet
     * @return
     */
    public List<SimpleUser> simpleList(int department, boolean fetchChild, Set<UserStatus> statusSet) {
        int status = 0;
        if (statusSet != null && statusSet.size() > 0) {
            for (UserStatus userStatus : statusSet) {
                status = status + userStatus.getStatus();
            }
        }

        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?department_id=%s&fetch_child=%s&status=%s";
        String user = wxClient.get(String.format(url, department, fetchChild ? "1" : "0", status));

        SimpleUserList simpleUserList = JSONUtil.fromJson(user, SimpleUserList.class);
        return simpleUserList.getUsers();
    }

    /**
     * 获取部门内（包含子部门）的所有用户
     * @param department
     * @return
     */
    public List<SimpleUser> simpleList(int department) {
        return simpleList(department, true, null);
    }

    /**
     * 获取部门内（是否包含子部门）中各状态的用户列表（详细）
     * @param department
     * @param fetchChild
     * @param statusSet
     * @return
     */
    public List<ReadUser> list(int department, boolean fetchChild, Set<UserStatus> statusSet) {
        int status = 0;
        if (statusSet != null && statusSet.size() > 0) {
            for (UserStatus userStatus : statusSet) {
                status = status + userStatus.getStatus();
            }
        }
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?department_id=%s&fetch_child=%s&status=%s";
        String user = wxClient.get(String.format(url, department, fetchChild ? "1" : "0", status));
        ReadUserList readUserList = JSONUtil.fromJson(user, ReadUserList.class);
        return readUserList.getUsers();
    }

    /**
     * 获取企业号下所有用户（详细）
     * @return
     */
    public List<ReadUser> list() {
        return list(1, true, null);
    }

    /**
     * 获取指定部门下（含子部门）所有用户详情
     * @param department
     * @return
     */
    public List<ReadUser> list(int department) {
        return list(department, true, null);
    }

    public void delete(List<String> users) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete";
        String json = String.format("{\"useridlist\":\"%s\"}", JSONUtil.toJson(users));
        wxClient.post(url, json);
    }
/** 已失效
    @Deprecated
    public Invitation invite(String uid) {
        String url = WxEndpoint.get("url.user.invite");
        String json = "{\"userid\":\"%s\"}";

        try {
            String response = wxClient.post(url, String.format(json, uid));
            Map<String, Object> result = JSONUtil.fromJson(response, Map.class);
            if (result.containsKey("type")) {
                return Invitation.format(Integer.valueOf(result.get("type").toString()));
            } else {
                return Invitation.FAILED;
            }
        } catch (Exception e) {
            if (e instanceof WxRuntimeException) {
                WxRuntimeException wxRuntimeException = (WxRuntimeException) e;
                if (60119 == wxRuntimeException.getCode()) {
                    return Invitation.ALREADY_FOLLOWED;
                }
                if (45025 == wxRuntimeException.getCode()) {
                    return Invitation.ALREADY_INVITED;
                }
            }
            return Invitation.FAILED;
        }

    }
*/
    /**
     * 详细用户列表
     */
    public static class ReadUserList {


        @JSONField(name = "userlist")
        private List<ReadUser> users;

        public List<ReadUser> getUsers() {
            return users;
        }

        public void setUsers(List<ReadUser> users) {
            this.users = users;
        }
    }

    /**
     * 简单用户列表
     */
    public static class SimpleUserList {

        @JSONField(name = "userlist")
        private List<SimpleUser> users;

        public List<SimpleUser> getUsers() {
            return users;
        }

        public void setUsers(List<SimpleUser> users) {
            this.users = users;
        }

    }
}
